package com.avic.rong.utils;

/**
 * Creater: Created by wangyz on 2017/1/21.
 * Email: 936804097@qq.com
 */

/*  * 文 件 名:  DataCleanManager.java  * 描    述:  主要功能有清除内/外缓存，清除数据库，清除sharedPreference，清除files和清除自定义目录  */

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;

import com.avic.rong.MyApplication;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;

import java.io.File;

/**
 * 本应用数据清除管理器
 */
public class DataCleanManager {
    /**
     * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache) * * @param context
     */
    public static void cleanInternalCache(Context context) {
        deleteFilesByDirectory(context.getCacheDir());
        deleteDir(context.getCacheDir());
    }

    /**
     * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases) * * @param context
     */
    public static void cleanDatabases(Context context) {
        deleteFilesByDirectory(new File("/data/data/"
                + context.getPackageName() + "/databases"));
    }

    /**
     * * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) * * @param
     * context
     */
    public static void cleanSharedPreference(Context context) {
        deleteFilesByDirectory(new File("/data/data/"
                + context.getPackageName() + "/shared_prefs"));
    }

    /**
     * 按名字清除本应用数据库 * * @param context * @param dbName
     */
    public static void cleanDatabaseByName(Context context, String dbName) {
        context.deleteDatabase(dbName);
    }

    /**
     * 清除/data/data/com.xxx.xxx/files下的内容 * * @param context
     */
    public static void cleanFiles(Context context) {
        deleteFilesByDirectory(context.getFilesDir());
        deleteDir(context.getFilesDir());
    }

    /**
     * * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache) * * @param
     * context
     */
    public static void cleanExternalCache(Context context) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            deleteFilesByDirectory(context.getExternalCacheDir());
            deleteDir(context.getExternalCacheDir());
//            context.getCacheDir()
        }
    }

    /**
     * 清除自定义路径下的文件，使用需小心，请不要误删。而且只支持目录下的文件删除 * * @param filePath
     */
    public static void cleanCustomCache(String filePath) {
        deleteFilesByDirectory(new File(filePath));
    }

    /**
     * 清除本应用所有的数据 * * @param context * @param filepath
     */
    public static void cleanApplicationData(Context context, String... filepath) {
        cleanInternalCache(context);
        cleanExternalCache(context);
//        cleanDatabases(context);
        cleanExternalCacheDir(context);
//        cleanSharedPreference(context);
        cleanFiles(context);

        for (String filePath : filepath) {
            cleanCustomCache(filePath);
        }
    }

    /**
     * 2.2以上的版本才有ExternalCacheDir
     *
     * @param context
     */
    public static void cleanExternalCacheDir(Context context) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
            File externalCacheDir = context.getExternalCacheDir();
            deleteFilesByDirectory(externalCacheDir);
            deleteDir(externalCacheDir);
        }
    }

    /**
     * 清除Glide图片磁盘缓存
     */
    public void clearImageDiskCache() {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.get(MyApplication.getInstance()).clearDiskCache();
                    }
                }).start();
            } else {
                Glide.get(MyApplication.getInstance()).clearDiskCache();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除Glide图片内存缓存
     */
    public void clearImageMemoryCache() {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行
                Glide.get(MyApplication.getInstance()).clearMemory();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String caculateCache(Context context) {

        long fileSize = 0;
        String cacheSize = "0KB";
        File fileDir = context.getFilesDir();
        File cacheDir = context.getCacheDir();

        fileSize += FileUtil.getDirSize(fileDir);
        fileSize += FileUtil.getDirSize(cacheDir);
        // 2.2版本才有将应用缓存转移到sd卡的功能
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
            File externalCacheDir = context.getExternalCacheDir();
            fileSize += FileUtil.getDirSize(externalCacheDir);
        }

        // glide 缓存的文件
//        GlideUtil.getInstance().


        if (fileSize > 0) {
            cacheSize = FileUtil.formatFileSize(fileSize);
        }

        return cacheSize;
    }


    /**
     * 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理 * * @param directory
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        // The directory is now empty so delete it
        return dir.delete();
    }


    /**
     * 获取glide缓存图片目录
     *
     * @param context
     * @param url
     */
    public static void getImgPathFromCache(final Context context, final String url) {
        new Thread() {
            @Override
            public void run() {
                FutureTarget<File> futureTarget = Glide.with(context).load(url).downloadOnly(100, 100);
                try {
                    File cacheFile = futureTarget.get();
                    String path = cacheFile.getAbsolutePath();
                } catch (Exception e) {
                }

            }
        }.start();
    }
}